<template>
  <Modal
    v-model="visible"
    title="药品目录"
    width="900"
    :mask-closable="false"
    @on-cancel="handleClose"
  >
    <!-- 搜索和筛选区域 -->
    <div class="search-area">
      <Row :gutter="16">
        <Col span="16">
          <Input
            v-model="searchQuery"
            placeholder="请输入药品名称或编码搜索"
            search
            @on-search="handleSearch"
            clearable
          >
            <Icon type="ios-search" slot="prefix" />
          </Input>
        </Col>
        <Col span="8">
          <Button type="primary" @click="handleSearch">查询</Button>
          <Button style="margin-left: 8px" @click="handleReset">重置</Button>
        </Col>
      </Row>
    </div>

    <!-- 药品列表 -->
    <div class="medicine-list">
      <Table 
        :loading="loading" 
        :columns="columns" 
        :data="medicineList" 
        :height="400"
        style="width: 100%"
      >
        <template slot-scope="{ row }" slot="stock">
          <span :class="{ 'low-stock': row.stock <= 100, 'out-of-stock': row.stock <= 0 }">
            {{ row.stock }}
          </span>
        </template>
      </Table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <Page
        :total="total"
        :current="currentPage"
        :page-size="pageSize"
        show-total
        show-elevator
        @on-change="handlePageChange"
      />
    </div>

    <div slot="footer">
      <Button @click="handleClose">关闭</Button>
    </div>
  </Modal>
</template>

<script>
import { getMedicineList } from '@/api/prescription'

export default {
  name: 'MedicineModal',
  props: {
    value: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      visible: false,
      loading: false,
      searchQuery: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      medicineList: [],
      columns: [
        { title: '药品编码', key: 'id', width: 80 },
        { title: '药品名称', key: 'name', width: 160 },
        { title: '规格', key: 'specification', width: 120 },
        { title: '单位', key: 'unit', width: 60 },
        { title: '类别', key: 'category', width: 100 },
        { title: '生产厂家', key: 'manufacturer', width: 140 },
        { 
          title: '价格', 
          key: 'price', 
          width: 80,
          render: (h, params) => {
            return h('span', `￥${params.row.price.toFixed(2)}`);
          }
        },
        { 
          title: '库存', 
          slot: 'stock',
          width: 80,
          sortable: true 
        }
      ]
    }
  },
  watch: {
    value(val) {
      this.visible = val;
    },
    visible(val) {
      this.$emit('input', val);
      if (!val) {
        // 关闭时清空数据
        this.searchQuery = '';
        this.currentPage = 1;
        this.medicineList = [];
        this.total = 0;
      }
    }
  },
  methods: {
    async loadMedicineList() {
      if (!this.searchQuery.trim()) {
        return;
      }

      this.loading = true;
      try {
        console.log('执行搜索，关键词:', this.searchQuery);
        const response = await getMedicineList(this.searchQuery.trim());
        console.log('药品列表查询结果:', response);
        
        if (response.success) {
          this.medicineList = response.result.map(item => ({
            ...item,
            price: Number(item.price) || 0,
            stock: Number(item.stock) || 0
          }));
          this.total = response.result.length;
          
          if (this.medicineList.length === 0) {
            this.$Message.info('未找到符合条件的药品');
          }
        } else {
          throw new Error(response.message || '获取药品列表失败');
        }
      } catch (error) {
        console.error('加载药品列表失败:', error);
        this.$Message.error('加载药品列表失败: ' + (error.message || '未知错误'));
      } finally {
        this.loading = false;
      }
    },
    
    handleSearch() {
      this.currentPage = 1;
      this.loadMedicineList();
    },
    
    handleReset() {
      this.searchQuery = '';
      this.currentPage = 1;
      this.medicineList = [];
      this.total = 0;
    },
    
    handlePageChange(page) {
      console.log('切换到页码:', page);
      this.currentPage = page;
      this.loadMedicineList();
    },
    
    handleClose() {
      this.visible = false;
    }
  }
}
</script>

<style scoped>
.search-area {
  margin-bottom: 16px;
}

.medicine-list {
  margin: 16px 0;
  overflow: hidden;
  
  :deep(.ivu-table-wrapper) {
    border-radius: 4px;
  }
  
  :deep(.ivu-table) {
    width: 100% !important;
    
    &-body {
      overflow-x: hidden !important;
    }
    
    &-header {
      overflow-x: hidden !important;
    }
    
    table {
      width: 100% !important;
    }
  }
}

.pagination {
  margin-top: 16px;
  text-align: right;
}

.low-stock {
  color: #ff9900;
}

.out-of-stock {
  color: #ed4014;
}

/* 确保模态框内的表格不会溢出 */
:deep(.ivu-modal-body) {
  max-height: calc(90vh - 150px);
  overflow: hidden;
}

.ivu-btn {
  margin-right: 8px;
}
</style> 